/**
 * Created by Administrator on 2016/5/26.
 */
var generic_pool = require('generic-pool');

var dbConf = require('./conf/db');


/**
 * mysql���ӳ�
 * @constructor
 */
function GenericPooling() {
    this.pool = null;
    this.init();
}


GenericPooling.prototype.init = function() {
    if(!this.pool) {
        this.pool = generic_pool.Pool({
            name: 'mysql',
            max: 30,
            create: function(callback) {
                var Client = require('mysql').createConnection({
                    host     : dbConf.mysql.host,
                    user     : dbConf.mysql.user,
                    password : dbConf.mysql.password,
                    database : dbConf.mysql.database,
                    port     : dbConf.mysql.port,
                    charset  :   'UTF8_GENERAL_CI'
                });
                callback(null,Client);
            },
            destroy: function(db) {
                db.destroy();
            }
        });
    }
};

/**
 * ��ȡ��ǰ���ӳ�
 * @returns {null|*}
 */
GenericPooling.prototype.getPool = function() {
    return this.pool;
};


GenericPooling.prototype.getConn = function(callback) {
    this.pool.acquire(function(err, conn) {
        if(err) {
            logger.writeLogError(err);
            callback(err);
        } else {
            callback(conn);
        }
    });
};

//pool.acquire(function(err, client) {
//    if (err) {
//        // handle error - this is generally the err from your
//        // factory.create function
//    }
//    else {
//        client.query("select * from gs_scrapy", [], function(err,data) {
//            console.log(data);
//            // return object back to pool
//            pool.release(client);
//        });
//    }
//});

var pooling = module.exports = exports = new GenericPooling();
